package com.newworld.dmsapp2.activity;

//import static android.support.v4.app.FragmentActivity.TAG;
import io.yunba.android.manager.YunBaManager;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.MainHomeFragment;
import com.newworld.dmsapp2.fragment.MainMessageFragment;
import com.newworld.dmsapp2.fragment.MainSettingFragment;
import com.newworld.dmsapp2.service.ServiceMessageUpdate;
import com.newworld.dmsapp2.ui.view.BadgeView;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.InitFunctionUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class MainActivity extends BaseActivity {
	private BadgeView badgemessage;
	private final static String TAG = "MainActivity";
	private Fragment[] mFragments;
	private RadioGroup bottomRg;
	private FragmentManager fragmentManager;
	private FragmentTransaction fragmentTransaction;
	@SuppressWarnings("unused")
	private RadioButton main_radio_home, main_radio_message,
			main_radio_setting;
	private Button main_bt_message;
	private User user;
	private String username = "";
	private BadgeView messagebadge;
	
	//private MessageReceiver mMessageReceiver;
	public final static String MESSAGE_RECEIVED_ACTION = "io.yunba.example.msg_received_action";
	public final static String CONNECT_STATUS = "connect_status";
	//public static boolean INIT_FRAGMENT = false;
	
	UpdateUIBroadcastReceiver broadcastReceiver;  

    private FragmentTransaction transaction;
    
    public static int unreadnum = 0;
    private Intent intent;
    private Bundle bundle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		initData();
		initViews();
		initEvents();

	}
	
	private void initData(){
		user = SingleSample.getInstance(MainActivity.this)
				.getUser();
		username = user.getUsername();
		fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        Fragment fragment = new MainHomeFragment();
        transaction.replace(R.id.content, fragment);
        transaction.commit();
        InitFunctionUtil intfun = new InitFunctionUtil(MainActivity.this);
        intfun.initFunctionData();
	}

	@Override
	protected void initViews() {
		setTitlebarNone(this, "主页面");
		/*Intent resultintent = getIntent();
		Bundle bundle = resultintent.getExtras();
		String messageid = bundle.getString("messageid");
		System.out.println("messageid"+messageid);
		message = messageid;*/
		
		bottomRg = (RadioGroup) findViewById(R.id.main_radiogroup);
		main_radio_home = (RadioButton) findViewById(R.id.main_radio_home);
		main_radio_message = (RadioButton) findViewById(R.id.main_radio_message);
		main_radio_setting = (RadioButton) findViewById(R.id.main_radio_setting);
		main_bt_message = (Button)findViewById(R.id.main_bt_message);
		mFragments = new Fragment[5];
		fragmentManager = getSupportFragmentManager();
		
		
		
		remind(main_bt_message);
		System.out.println("unreadnum--1"+unreadnum);
		setReciever();
		
		
		/*mFragments[0] = fragmentManager
				.findFragmentById(R.id.main_fragment_home);
		mFragments[1] = fragmentManager
				.findFragmentById(R.id.main_fragment_message);
		mFragments[2] = fragmentManager
				.findFragmentById(R.id.main_fragment_setting);
		fragmentTransaction = fragmentManager.beginTransaction()
				.hide(mFragments[0]).hide(mFragments[1]).hide(mFragments[2]);*/
		/*if(message.equals("1")){
			fragmentTransaction.show(mFragments[1]).commit();
		}else{*/
			/*fragmentTransaction.show(mFragments[0]).commit();*/
		//	}
		
		if (!MyPreference.getInstance(MainActivity.this).getServerUrl()
				.equals("")) {
			Config.SERVER_URL = MyPreference.getInstance(MainActivity.this)
					.getServerUrl();
		}
		 
		if (Tool.isNetworkAvailable(MainActivity.this)) {
			 initYunBa();
		}else{
			showShortToast("请开启网络，重新登录");
		}

	}
	/**
	 * 创建消息提醒view
	 * @param view
	 */
	private void remind(View view) { //BadgeView的具体使用 
		messagebadge = new BadgeView(this, view);// 创建一个BadgeView对象，view为你需要显示提醒的控件
		messagebadge.setText(unreadnum+""); // 需要显示的提醒类容
		messagebadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);// 显示的位置.右上角,BadgeView.POSITION_BOTTOM_LEFT,下左，还有其他几个属性
		messagebadge.setTextColor(Color.WHITE); // 文本颜色
		messagebadge.setBadgeBackgroundColor(Color.RED); // 提醒信息的背景颜色，自己设置
		messagebadge.setTextSize(12); // 文本大小
		//messagebadge.setBadgeMargin(3, 3); // 水平和竖直方向的间距
		messagebadge.setBadgeMargin(60,10); //各边间隔
		// messagebadge.toggle(); //显示效果，如果已经显示，则影藏，如果影藏，则显示
		if(unreadnum == 0){
			messagebadge.hide();//影藏显示
		}else{
			messagebadge.show();// 只有显示	
		}
		
	}
	
	/**
	 * 动态注册广播,启动服务（消息提醒）
	 */
	private void setReciever(){
		 // 动态注册广播  
        IntentFilter filter = new IntentFilter();  
        filter.addAction(Config.SERVICE_MESSAGE_UPDATENUM);  
        broadcastReceiver = new UpdateUIBroadcastReceiver();  
        registerReceiver(broadcastReceiver, filter);  
  
        // 启动服务  
        bundle = new Bundle();
        bundle.putInt("count", unreadnum);
        intent = new Intent(this, ServiceMessageUpdate.class);  
        intent.putExtras(bundle);
        startService(intent);  
	}
	private void initYunBa() {
		// 初始化云巴
		YunBaManager.start(getApplicationContext());

		YunBaManager.subscribe(getApplicationContext(),
				new String[] { "xiang" }, new IMqttActionListener() {

					@Override
					public void onSuccess(IMqttToken arg0) {
						Log.d(TAG, "Subscribe topic succeed");
					}

					@Override
					public void onFailure(IMqttToken arg0, Throwable arg1) {
						Log.d(TAG, "Subscribe topic failed");
					}
				});

		// 设置自己的别名alias
		// final String alias = "ahz001";
		// 根据登录角色获取别名alias
		final String alias = username;
		YunBaManager.setAlias(getApplicationContext(), alias,
				new IMqttActionListener() {

					@Override
					public void onSuccess(IMqttToken arg) {
						StringBuilder showMsg = new StringBuilder();
						showMsg.append("[Demo] setAlias alias ").append(" = ")
								.append(alias).append(" succeed");
						System.out.println("showMsg" + showMsg);
						// setCostomMsg(showMsg.toString());
					}

					@Override
					public void onFailure(IMqttToken arg0, Throwable arg) {
						StringBuilder showMsg = new StringBuilder();
						showMsg.append("[Demo] setAlias alias ").append(" = ")
								.append(alias).append(" failed");
						System.out.println("showMsg" + showMsg);
						// setCostomMsg(showMsg.toString());
					}
				});
	}
	
	@Override
	protected void initEvents() {

		bottomRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				/*fragmentTransaction = fragmentManager.beginTransaction()
						.hide(mFragments[0]).hide(mFragments[1])
						.hide(mFragments[2]);*/
				switch (checkedId) {
				/*case R.id.main_radio_home:
					//INIT_FRAGMENT = false;
					setTitlebarNone(MainActivity.this, "主页面");
					fragmentTransaction.show(mFragments[0]).commit();
					break;

				case R.id.main_radio_message:
					//INIT_FRAGMENT = true;
					setTitlebarNone(MainActivity.this, "消息");
					fragmentTransaction.show(mFragments[1]).commit();
					break;

				case R.id.main_radio_setting:
					//INIT_FRAGMENT = false;
					setTitlebarNone(MainActivity.this, "设置");
					fragmentTransaction.show(mFragments[2]).commit();
					break;*/
				case R.id.main_radio_home:
					setTitlebarNone(MainActivity.this, "主页面");
					transaction = fragmentManager.beginTransaction();
	                Fragment homeFragment = new MainHomeFragment();
	                transaction.replace(R.id.content, homeFragment);
	                transaction.commit();
					break;
				case R.id.main_radio_message:
					setTitlebarNone(MainActivity.this, "消息");
					transaction = fragmentManager.beginTransaction();
	                Fragment messageFragment = new MainMessageFragment();
	                transaction.replace(R.id.content, messageFragment);
	                transaction.commit();
	                
	    	    	messagebadge.setText(String.valueOf(unreadnum));  
	    	    	if(unreadnum == 0){
	    				messagebadge.hide();//影藏显示
	    			}else{
	    				messagebadge.show();// 只有显示	
	    			}
					break;
				case R.id.main_radio_setting:
					setTitlebarNone(MainActivity.this, "设置");
					transaction = fragmentManager.beginTransaction();
	                Fragment settingFragment = new MainSettingFragment();
	                transaction.replace(R.id.content, settingFragment);
	                transaction.commit();
					break;

				default:
					break;
				}
			}
		});
	}
	
	/** 
	 * 定义广播接收器（内部类） 
	 *  
	 * @author lenovo 
	 *  
	 */  
	public class UpdateUIBroadcastReceiver extends BroadcastReceiver {  

	    @Override  
	    public void onReceive(Context context, Intent intent) {  
	    	unreadnum = intent.getExtras().getInt("count"); 
	    	messagebadge.setText(String.valueOf(unreadnum));  
	    	if(unreadnum == 0){
				messagebadge.hide();//影藏显示
			}else{
				messagebadge.show();// 只有显示	
			}
	    }  

	}  

	@Override  
	protected void onDestroy() {  
	    System.out.println("onDestroy");  
	    super.onDestroy();  
	    // 注销广播  
	    unregisterReceiver(broadcastReceiver);  
	}  
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			//禁止关闭程序
			 moveTaskToBack(false);  
	         return true;  
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
}
